package org.jfonia.connect5.gui;

import java.awt.Graphics;
import java.awt.Point;
import java.awt.geom.Line2D;
import javax.swing.JComponent;
import org.jfonia.connect5.basics.BasicValueNode;
import org.jfonia.connect5.basics.Node;
import org.jfonia.connect5.basics.Observer;

/**
 * @author wijnand.schepens@hogent.be
 */
public class Line extends JComponent implements Observer
{
	BasicValueNode<Integer> x1Node, y1Node, x2Node, y2Node;
	

	public Line(BasicValueNode<Integer> x1Node, BasicValueNode<Integer> y1Node, BasicValueNode<Integer> x2Node, BasicValueNode<Integer> y2Node)
	{
		this.x1Node = x1Node;
		this.y1Node = y1Node;
		this.x2Node = x2Node;
		this.y2Node = y2Node;
		x1Node.addObserver(this);
		y1Node.addObserver(this);
		x2Node.addObserver(this);
		y2Node.addObserver(this);

		updateSize();
		//this.setSize(new Dimension(100,100));  // needed to force draw. TODO...
//		this.setSize(getSize());  // needed to force draw. TODO...
	}

	public int getX1()
	{
		return x1Node.getValue();
	}

	public int getX2()
	{
		return x2Node.getValue();
	}

	public int getY1()
	{
		return y1Node.getValue();
	}

	public int getY2()
	{
		return y2Node.getValue();
	}


	public void updateSize()
	{
		System.out.println("setSize " + Math.abs(x2Node.getValue()-x1Node.getValue()) + ",  " + Math.abs(y2Node.getValue()-y1Node.getValue()));
		setSize(Math.abs(x2Node.getValue()-x1Node.getValue()) + 50, Math.abs(y2Node.getValue()-y1Node.getValue()) + 50);
	}

//	public Dimension getSize()
//	{
//		return new Dimension(Math.abs(x2Node.getValue()-x1Node.getValue()), Math.abs(y2Node.getValue()-y1Node.getValue()));
//	}

	@Override
	public void paintComponent(Graphics g)
	{
		//this.setSize(getSize());  // needed to force draw. TODO...
		g.drawLine(x1Node.getValue(), y1Node.getValue(), x2Node.getValue(), y2Node.getValue());
	}
//	public void paint(Graphics2D g)
//	{
//		g.drawLine(x1Node.getValue(), y1Node.getValue(), x2Node.getValue(), y2Node.getValue());
//	}

	public boolean contains(Point p)
	{
		return Line2D.ptSegDistSq(getX1(), getY1(), getX2(), getY2(), p.x, p.y) < 2;
	}

	public void onNotify(Object source)
	{
		updateSize();
		repaint();
	}


}
